package org.geektimes.projects.user.config;

import org.apache.commons.io.IOUtils;
import org.eclipse.microprofile.config.spi.ConfigSource;
import org.geektimes.projects.user.support.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * properties文件配置源
 *
 * @author : lsq
 */
@Component
public class PropertiesConfigSource implements ConfigSource {

	private String localPath = "META-INF/application.properties";


	private final Map<String, String> properties = new HashMap<>();


	@PostConstruct
	public void init(){
		if (properties.isEmpty() && this.localPath != null) {
			InputStream resourceAsStream = null;
			try {
				resourceAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(localPath);
				if (resourceAsStream == null){
					return;
				}
				Properties p = new Properties();
				p.load(resourceAsStream);
				Enumeration<String> enumeration = (Enumeration<String>) p.propertyNames();
				while (enumeration.hasMoreElements()) {
					String name = enumeration.nextElement();
					this.properties.put(name, (String) p.get(name));
				}
				properties.put(CONFIG_ORDINAL , "200");
			} catch (IOException e) {
				throw new IllegalStateException(e);
			} finally {
				IOUtils.closeQuietly(resourceAsStream);
			}
		}
	}


	@Override
	public Set<String> getPropertyNames() {
		return properties.keySet();
	}

	@Override
	public String getValue(String propertyName) {
		return properties.get(propertyName);
	}

	@Override
	public String getName() {
		return "properties-config";
	}
}
